<template>
    <div class="main-todo">
        <input class="add-todo"
               placeholder="what to do?"
               autofocus type="text"
               @keyup.enter="addTodo"
               v-model="content"
        />
        <todo-item v-for="(item,index) in filterData" :key="index" :todo="item" @del="handlerDelItem"></todo-item>
        <todo-info :total="total" @toggleState="handlerToggleState" @clearCompleted="handlerClearCompleted"></todo-info>
    </div>
</template>

<script>
    import TodoItem from './coms/TodoItem.vue';
    import TodoInfo from './coms/TodoInfo.vue';
    let id = 0;
    export default {
        name: "MainTodo",
        data(){
            return {
                todoData:[],
                content:'',
                total:0,
                filter: 'all',
            }
        },
        methods : {
            addTodo(){
                if(this.content === '') return;
                this.todoData.unshift({
                    id: id++,
                    content: this.content,
                    completed: false
                });
                this.content = '';
            },
            handlerDelItem(id){
                this.todoData.splice(this.todoData.findIndex(item => item.id === id), 1);
            },
            handlerToggleState(state){
                this.filter = state;
            },
            handlerClearCompleted(){
                this.todoData = this.todoData.filter(item => item.completed === false);
            }
        },
        //监听器
        watch:{
            //监听todoData
          todoData: {
              /**
               * deep的意思就是深入观察，监听器会一层层的往下遍历，给对象的所有属性都加上这个监听器，
               * 但是这样性能开销就会非常大了，任何修改obj里面任何一个属性都会触发这个监听器里的 handler。
               */
              deep: true,
              //当todoData发生变化调用handler
              handler(){
                  this.total = this.todoData.filter(item => item.completed === false).length;
              }
          }
        },
        computed : {
            filterData() {
                switch (this.filter) {
                    case 'all':
                        return this.todoData;
                    case 'active':
                        return this.todoData.filter(item => item.completed === false);
                    case 'completed':
                        return this.todoData.filter(item => item.completed === true);
                }
            }
        },
        components : {
            TodoItem,
            TodoInfo,
        }
    }
</script>

<style scoped>
    .main-todo{
        width: 600px;
        margin:  0 auto;
        background-color: #fff;
        box-shadow: 0 0 5px #666;
    }
    .add-todo {
        font-size: 24px;
        font-weight: inherit;
        font-family: inherit;
        color: inherit;
        border: none;
        outline: none;
        width: 100%;
        padding: 16px 16px 16px 36px;
        box-sizing: border-box;
    }
</style>